package pub.guoxin.oops.manager.service.impl;

import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import pub.guoxin.oops.manager.service.AlarmInfoService;
import pub.guoxin.oops.manager.vo.AlarmInfoStatisticsVo;
import pub.guoxin.oops.model.AlarmInfo;
import pub.guoxin.oops.repository.AlarmInfoRepository;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Create by guoxin on 2018/5/6
 */
@Service
public class AlarmInfoServiceImpl implements AlarmInfoService {

    @Autowired
    private AlarmInfoRepository alarmInfoRepository;

    @Override
    public Map<String, Object> statistics(String alarmDisposeId) {
        Map<String, Object> maps = Maps.newHashMap();
        List<AlarmInfo> alarmInfos = alarmInfoRepository.findByAlarmDisposeIdOrderByCreationAsc(alarmDisposeId);
        List<AlarmInfoStatisticsVo> collect = alarmInfos.stream().map(AlarmInfoStatisticsVo::new).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(collect)) {
            LocalDateTime first = collect.get(0).getCreation();
            LocalDateTime last = collect.get(collect.size() - 1).getCreation();
            long diff = ChronoUnit.DAYS.between(first, last);
            LocalDateTime localDateTime = Instant.ofEpochMilli(diff).atZone(ZoneId.systemDefault()).toLocalDateTime();
            maps.put("timeDiff", localDateTime);
        } else {
            maps.put("timeDiff", null);
        }
        maps.put("collect", collect);
        return maps;
    }

}
